﻿/* 
 *  <copyright file="BaseScene.cs" company="Wesley Jowitt">
 *  
 *  SobrietyEngine: Copyright (c) 2011 Wesley Jowitt
 *  
 *  This software is distributed under a software license.
 *   * As of the creation time of this file, the license in use is the Microsoft Permissive License (Ms-PL) 
 *    * The license can be viewed at:
 *     * License.Txt in the root folder of this project
 *      * http://sobrietyengine.codeplex.com/license
 *       * http://www.microsoft.com/opensource/licenses.mspx
 *       
 *  </copyright>
 *   */

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using SobrietyEngine.Actor;
using SobrietyEngine.Components;
using SobrietyEngine.Components.Controller;
using SobrietyEngine.Guids;
using SobrietyEngine.PlayerData;

namespace SobrietyEngine.Scene
{
    public abstract class BaseScene: IScene 
    {
        protected List<IActor> Actors;

        public Boolean Active { get; set; }
        public Boolean Debug { get; set; }
        public Boolean Paused { get; private set; }

        protected SpriteBatch spriteBatch;
        protected IGraphicsDeviceService graphicsDevice;
        public IGraphicsDeviceService GraphicDeviceService { get { return graphicsDevice; } }

        PlayerGameService playerGameService = null;

        public Viewport FullscreenViewport { get; set; }

        public Texture2D SplitscreenOverlay { get; set; }

        protected Dictionary<Type, List<SobrietyEngine.Components.IComponent>> ComponentsByIfaceType;

        public Vector3 ActorPositionLimit { get; set; }

        protected Game game;

        public String Name { get; set; }       

        public BaseScene(string sceneName, Game _game)
        {
            Actors = new List<IActor>();
            ComponentsByIfaceType = new Dictionary<Type, List<SobrietyEngine.Components.IComponent>>();
            ComponentsByIfaceType.Add(typeof(IGraphic2D), new List<SobrietyEngine.Components.IComponent>());
            ComponentsByIfaceType.Add(typeof(IGraphic3D), new List<SobrietyEngine.Components.IComponent>());
            ComponentsByIfaceType.Add(typeof(ICamera), new List<SobrietyEngine.Components.IComponent>());
            game = _game;
            FullscreenViewport = game.GraphicsDevice.Viewport;
            Active = true;
            Name = sceneName;
            ActorPositionLimit = new Vector3(1000,1000,1000);
        }

        public abstract void Remove();

        public void Initialize()
        {
            graphicsDevice = (IGraphicsDeviceService)game.Services.GetService(typeof(IGraphicsDeviceService));
            spriteBatch = new SpriteBatch(graphicsDevice.GraphicsDevice);
            playerGameService = (PlayerGameService)game.Services.GetService(typeof(PlayerGameService));
        }


        public void TogglePause()
        {
            Pause(!Paused);
        }

        public void Pause(Boolean pause)
        {
            //paused essentially means we have set all objects to 'active is false'
            //and removed all event listeners
            foreach (IActor actor in Actors)
            {
                if (pause)
                {
                    actor.UnregisterEventListeners();
                    actor.UpdateActor = false;                    
                }
                else
                {
                    actor.RegisterEventListeners();
                    actor.UpdateActor = true;                    
                }                
            }
        }

        public void RegisterComponent(SobrietyEngine.Components.IComponent Component)
        {            
            Type[] supportedIFace = Component.SupportedInterfaces();

            foreach (Type type in supportedIFace)
            {
                List<SobrietyEngine.Components.IComponent> temp;
                if (!ComponentsByIfaceType.TryGetValue(type, out temp))
                {
                    temp = new List<SobrietyEngine.Components.IComponent>();
                    ComponentsByIfaceType.Add(type, temp);
                }
                temp.Add(Component);
            }
        }

        public void RegisterComponents(IActor actor)
        {
            //foreach (SobrietyEngine.Components.IComponent c in actor.GetComponents().Values)
            foreach (List<SobrietyEngine.Components.IComponent> l in actor.GetComponents().Values)
            {
                foreach (SobrietyEngine.Components.IComponent c in l)
                {
                    RegisterComponent(c);
                }
            }
        }

        public void UnregisterComponent(SobrietyEngine.Components.IComponent Component)
        {
            Type[] supportedIfaces = Component.SupportedInterfaces();
            foreach (Type type in supportedIfaces)
            {
                if (ComponentsByIfaceType.ContainsKey(type))
                {
                    ComponentsByIfaceType[type].Remove(Component);
                }
            }
        }

        public void UnregisterComponents(IActor actor)
        {
            foreach (List<SobrietyEngine.Components.IComponent> cl in actor.GetComponents().Values)
                foreach(SobrietyEngine.Components.IComponent c in cl)
                    UnregisterComponent(c);
        }

        public IActor CreateEmptyActor()
        {
            IActor act = new BaseActor(game, this);
            Actors.Add(act);
            return act;
        }

        public IActor CreateActor(List<SobrietyEngine.Components.IComponent> ComponentList)
        {
            IActor temp = new BaseActor(game, this);
            foreach (SobrietyEngine.Components.IComponent i in ComponentList)
            {
                temp.AttachComponent(i);
                RegisterComponent(i);
            }
            temp.Initialize();
            Actors.Add(temp);
            return temp;
        }

        public void RemoveActor(CGuid guid)
        {
            RemoveActor((IActor)guid.Resolve());
        }

        public void RemoveActor(IActor actor)
        {
            CGuid guid = actor.Guid;

            //need to unregister all components
            UnregisterComponents(actor);

            //removes all components and the guid
            actor.Remove();

            //need to remove actor from list
            Actors.Remove(actor);
        }

        public virtual void Clear()
        {
            foreach (IActor act in Actors)
            {
                UnregisterComponents(act);
                act.UnregisterEventListeners();
                act.Remove();
            }
            Actors.Clear();
        }

        //OwningPlayerInfo opi;
        public void Update(GameTime gameTime)
        {
            foreach (IPosition pos in ComponentsByIfaceType[typeof(IPosition)])
            {
                if (pos.PositionV3.LengthSquared() > ActorPositionLimit.LengthSquared())
                    ((IComponent)pos).Actor.MarkedForRemoval = true;
            }
            for (int a = 0; a < Actors.Count; ++a)
            {
                if (Actors[a].MarkedForRemoval)
                    RemoveActor(Actors[a]);
                else
                    Actors[a].Update(gameTime);
            }
        }

        abstract public void ManualDraw(GameTime gameTime);
    
        public List<SobrietyEngine.Components.IComponent> GetComponents(Type type)
        {
            if (ComponentsByIfaceType.ContainsKey(type))
                return ComponentsByIfaceType[type];
            return null;
        }

        public void DisableControllers()
        {
            foreach (ControllerCmp cc in this.GetComponents(typeof(IController)))
            {
                cc.Enabled = false;
            }
        }

        public void EnableControllers()
        {
            if (this.GetComponents(typeof(IController)) == null)
                return;
            foreach (ControllerCmp cc in this.GetComponents(typeof(IController)))
            {
                cc.Enabled = true;
            }
        }
    }
}
